<template>
  <div class="quality-issues">
    <!-- 搜索区 -->
    <el-card class="mb-4" shadow="never">
      <el-form :inline="true" :model="searchForm" size="small">
        <el-form-item label="物料名称">
          <el-input v-model="searchForm.material" clearable placeholder="物料名称" />
        </el-form-item>
        <el-form-item label="责任人">
          <el-input v-model="searchForm.responsible" clearable placeholder="责任人" />
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" clearable placeholder="全部" style="width:140px;">
            <el-option label="待处理" value="待处理"/>
            <el-option label="处理中" value="处理中"/>
            <el-option label="已完成" value="已完成"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="openDialog('add')">登记问题</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 问题记录表格 -->
    <el-table :data="filteredData" border style="width:100%;">
      <el-table-column prop="material" label="物料名称" width="130"/>
      <el-table-column prop="batchNo" label="批次号" width="120"/>
      <el-table-column prop="desc" label="问题描述" width="150px"/>
      <el-table-column prop="failCount" label="不合格数量" width="110"/>
      <el-table-column prop="date" label="检验日期" width="120"/>
      <el-table-column prop="responsible" label="责任人" width="100"/>
      <el-table-column prop="status" label="处理状态" width="110">
        <template #default="{ row }">
          <el-tag
            :type="row.status==='待处理'?'danger':row.status==='处理中'?'warning':'success'"
            disable-transitions
          >
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240px">
        <template #default="{ row, $index }">
          <el-button size="small" @click="openDialog('edit', row, $index)">编辑</el-button>
          <el-button size="small" @click="changeStatus(row)">状态流转</el-button>
          <el-button size="small" type="danger" @click="handleDelete($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogMode==='add'?'登记质量问题':'编辑质量问题'" v-model="showDialog" width="500px">
      <el-form :model="dialogForm" :rules="dialogRules" ref="dialogFormRef" label-width="110px">
        <el-form-item label="物料名称" prop="material">
          <el-input v-model="dialogForm.material" />
        </el-form-item>
        <el-form-item label="批次号" prop="batchNo">
          <el-input v-model="dialogForm.batchNo" />
        </el-form-item>
        <el-form-item label="问题描述" prop="desc">
          <el-input v-model="dialogForm.desc" type="textarea" />
        </el-form-item>
        <el-form-item label="不合格数量" prop="failCount">
          <el-input-number v-model="dialogForm.failCount" :min="1" style="width:100%;" />
        </el-form-item>
        <el-form-item label="检验日期" prop="date">
          <el-date-picker v-model="dialogForm.date" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width:100%;" />
        </el-form-item>
        <el-form-item label="责任人" prop="responsible">
          <el-input v-model="dialogForm.responsible" />
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="dialogForm.status" style="width:100%">
            <el-option label="待处理" value="待处理"/>
            <el-option label="处理中" value="处理中"/>
            <el-option label="已完成" value="已完成"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitDialog">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// 模拟数据
const allData = ref(generateMock())
function generateMock() {
  const mat = ['对乙酰氨基酚', '头孢拉定原料', '葡萄糖', '维生素C粉', '乳糖']
  const person = ['王丽', '张伟', '李强', '赵敏', '刘晨']
  const arr = []
  for (let i = 0; i < 13; i++) {
    arr.push({
      material: mat[i % mat.length],
      batchNo: 'BN' + (1000 + i),
      desc: ['包装破损', '含量偏低', '杂质超标', '外观异常', '水分超标'][i % 5],
      failCount: Math.floor(Math.random() * 12) + 1,
      date: `2025-06-${String(i % 28 + 1).padStart(2, '0')}`,
      responsible: person[i % person.length],
      status: ['待处理', '处理中', '已完成'][i % 3]
    })
  }
  return arr
}

// 搜索相关
const searchForm = reactive({ material: '', responsible: '', status: '' })
const filteredData = computed(() =>
  allData.value.filter(row =>
    (!searchForm.material || row.material.includes(searchForm.material)) &&
    (!searchForm.responsible || row.responsible.includes(searchForm.responsible)) &&
    (!searchForm.status || row.status === searchForm.status)
  )
)
function handleSearch() {}
function resetSearch() {
  searchForm.material = ''
  searchForm.responsible = ''
  searchForm.status = ''
}

// 增删改查
const showDialog = ref(false)
const dialogMode = ref('add') // add / edit
const dialogForm = reactive({
  material: '', batchNo: '', desc: '', failCount: 1, date: '', responsible: '', status: '待处理'
})
const dialogRules = {
  material: [{ required: true, message: '必填', trigger: 'blur' }],
  batchNo: [{ required: true, message: '必填', trigger: 'blur' }],
  desc: [{ required: true, message: '必填', trigger: 'blur' }],
  failCount: [{ required: true, message: '必填', trigger: 'blur' }],
  date: [{ required: true, message: '必填', trigger: 'change' }],
  responsible: [{ required: true, message: '必填', trigger: 'blur' }],
  status: [{ required: true, message: '必填', trigger: 'change' }]
}
const dialogFormRef = ref()
let editingIdx = -1
function openDialog(mode, row, idx) {
  dialogMode.value = mode
  if (mode === 'add') {
    Object.assign(dialogForm, {
      material: '', batchNo: '', desc: '', failCount: 1, date: '', responsible: '', status: '待处理'
    })
  } else {
    Object.assign(dialogForm, { ...row })
    editingIdx = idx
  }
  showDialog.value = true
  nextTick(() => dialogFormRef.value && dialogFormRef.value.clearValidate())
}
function submitDialog() {
  dialogFormRef.value.validate(valid => {
    if (!valid) return
    if (dialogMode.value === 'add') {
      allData.value.unshift({ ...dialogForm })
      ElMessage.success('登记成功')
    } else {
      allData.value.splice(editingIdx, 1, { ...dialogForm })
      ElMessage.success('编辑成功')
    }
    showDialog.value = false
  })
}
function handleDelete(idx) {
  allData.value.splice(idx, 1)
  ElMessage.success('已删除')
}

// 状态流转
function changeStatus(row) {
  if (row.status === '待处理') row.status = '处理中'
  else if (row.status === '处理中') row.status = '已完成'
  else row.status = '待处理'
  ElMessage.success('状态已更新')
}
</script>

<style scoped>
.quality-issues {
  padding: 20px 16px;
}
.mb-4 { margin-bottom: 16px;}
</style>
